package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.constants.RedisConstants;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    IUserService iUserService;

    @Override
    public boolean follow(Long followId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.USER_FOLLOW_KEY + userId;

        if (isFollow) {
            // 关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followId);
            boolean success = save(follow);

            // 加入redis缓存
            if (Boolean.TRUE.equals(success)) {
                stringRedisTemplate.opsForSet().add(key, followId.toString());
            }
        } else {
            // 取关
            boolean success = remove(new QueryWrapper<Follow>()
                    .eq("user_id", UserHolder.getUser().getId())
                    .eq("follow_user_id", followId));
            if (Boolean.TRUE.equals(success)) {
                stringRedisTemplate.opsForSet().remove(key, followId.toString());
            }
        }
        return true;
    }

    @Override
    public Result getIsFollow(Long followId) {
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followId).count();
        return Result.ok(count >= 1);
    }

    @Override
    public Result commonFollow(Long followId) {
        // 取交集
        Long userId = UserHolder.getUser().getId();
        String key1 = RedisConstants.USER_FOLLOW_KEY + userId;
        String key2 = RedisConstants.USER_FOLLOW_KEY + followId;

        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        // 查询用户
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> userList = iUserService.query().in("id", ids).list();

        // 转为 List<UserDTO>
        List<UserDTO> userDTOS = intersect.stream()
                .map(item -> BeanUtil.copyProperties(userList, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
